<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}渠道API配置`"
    width="536"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div class="h-[460px]">
      <VForm
        ref="form"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :rules="rules"
        :disabled="disabled"
        :originOption="optionsData"
      >
        <template #sizeAppend>cm</template>
      </VForm>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? '关闭' : '取消' }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from 'element-plus'
import VForm from '@/components/Form/index.vue'
import { overallOptions } from '@/api/public'

import {
  logisticsChannelShipping,
  createLogisticsChannel,
  updateLogisticsChannel,
  logisticsChannelDetail,
} from '../api'

const props = defineProps({
  id: { type: [String, Number], default: '' },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
})

const emit = defineEmits(['update:modelValue', 'refresh', 'close'])

const formOption = {
  labelPosition: 'top',
  inline: true,
}

const rules = {
  logistics_api_id: [
    { required: true, message: '请选择物流商API', trigger: 'blur' },
  ],
  channel: [{ required: true, message: '请选择物流商渠道', trigger: 'blur' }],
  shipping: [
    { required: true, message: '请选择渠道运输方式', trigger: 'blur' },
  ],
}

const form = ref()
const model = ref({})
const loading = ref()
const optionsData = ref({})

const handleChangeAPi = async e => {
  const { logistics_api_id } = e
  const formValues = await form.value.getFormValues()
  const res = await logisticsChannelShipping({ logistics_api_id })
  if (res) {
    optionsData.value['shipping'] = res.data
  }
  model.value = {
    ...formValues,
    shipping: undefined,
    user_code: undefined,
  }
}

const handleChangeShipping = async e => {
  const formValues = await form.value.getFormValues()
  model.value = {
    ...formValues,
    user_code: e.use_code,
  }
}

onMounted(() => {
  getOption()
})

const getOption = async () => {
  const { data } = await overallOptions({
    params: ['map.logistics-api', 'map.channel'],
  })
  let _options = data['mapLogisticsApi']
  if (_options) {
    optionsData.value = data
  }
}

const fieldList = [
  {
    field: 'logistics_api',
    type: 'select',
    originField: 'mapLogisticsApi',
    label: '物流商API名称',
    options: {
      labelKey: 'api_name',
    },
    valueKey: 'logistics_api_id',
    itemProps: {
      onChange: handleChangeAPi,
    },
    full: true,
    itemStyle: { width: '100%' },
  },
  {
    field: 'channel',
    type: 'select',
    originField: 'mapChannel',
    options: {
      labelKey: 'channel_name',
    },
    valueKey: 'channel_id',
    label: '物流商渠道中文名称',
      full: true,
    itemStyle: { width: '100%' },
  },
  {
    field: 'shipping',
    label: '渠道运输方式中文名',
    type: 'select',
    originField: 'shipping',
    options: {
      labelKey: 'cn_name',
    },
    valueKey: 'id',
    itemProps: {
      onChange: handleChangeShipping,
    },
      full: true,
    itemStyle: { width: '100%' },
  },
  {
    field: 'user_code',
    label: '运输方式代码',
    disabled: true,
  },
  {
    field: 'size',
    label: '标签规格',
    append: 'sizeAppend',
  },
  {
    field: 'remark',
    label: '备注',
    type: 'textarea',
    autosize: { minRows: 4, maxRows: 8 },
    full: true,
    itemStyle: { width: '100%' },
  },
]

watch(
  () => props.id,
  val => {
    if (val) {
      nextTick(() => {
        getDetail(val)
      })
    }
  }
)

const getDetail = async id => {
  try {
    const { data } = await logisticsChannelDetail({ id })

    const { channel_id, logistics_api_id, logistics_api_shipping_id } = data
    await handleChangeAPi({ logistics_api_id })
    const _options = optionsData.value
    const logistics_api = _options['mapLogisticsApi'].find(
      n => n.logistics_api_id === logistics_api_id
    )
    const channel = _options['mapChannel'].find(
      n => n.channel_id === channel_id
    )
    console.warn(_options)
    const shipping = _options['shipping'].find(
      n => n.logistics_api_shipping_id === logistics_api_shipping_id
    )
    model.value = {
      ...data,
      logistics_api,
      channel,
      shipping,
    }
  } catch (e) {
    model.value = {}
    console.error(e)
  }
}

const isEdit = computed(() => {
  return !!props.id
})

const handleSave = async () => {
  try {
    const formInfo = await form.value.submit()
    console.warn(formInfo)
    const api = {
      edit: updateLogisticsChannel,
      add: createLogisticsChannel,
    }
    const { id } = props

    const { logistics_api, channel, shipping } = formInfo
    const { code, message } = await api[isEdit.value ? 'edit' : 'add']({
      id: id || undefined,
      ...formInfo,
      logistics_api_id: logistics_api?.id,
      channel_id: channel?.channel_id,
      logistics_id: channel?.logistics_id,
      logistics_api_shipping_id: shipping?.id,
    })
    if (code !== 200) {
      ElMessage.warning(message)
      return
    }
    ElMessage.success(isEdit.value ? '修改成功' : '保存成功')
    handleClose(true)
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning('请检查表单信息')
    }
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = async refresh => {
  model.value = {}
  await nextTick()
  form.value.resetForm()
  emit('update:modelValue', false)
  emit('close')
  if (refresh) emit('refresh')
}
</script>
